/*
 * Copyright (C) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "aki_class_cmp.h"

namespace AKITEST {

napi_value NapiClassTest::SetMsg(napi_env env, napi_callback_info info)
{
    napi_value result = nullptr;
    napi_get_undefined(env, &result);
    char msg[128] = {0};
    napi_value jsthis;
    napi_value msgvalue;
    napi_status status;
    size_t argc = 1, size = 0;
    if (napi_get_cb_info(env, info, &argc, &msgvalue, &jsthis, nullptr) != napi_ok) {
        return result;
    }
    NapiClassTest *obj;
    status = napi_unwrap(env, jsthis, (void **)&obj);
    if (napi_get_value_string_utf8(env, msgvalue, msg, sizeof(msg), &size) != napi_ok) {
        return result;
    }
    obj->testMsg = msg;
    return nullptr;
}

napi_value NapiClassTest::GetMsg(napi_env env, napi_callback_info info)
{
    napi_value result = nullptr;
    std::string msg = "hello NapiTest";
    napi_value jsthis;
    napi_status status;
    napi_get_undefined(env, &result);
    if (napi_get_cb_info(env, info, nullptr, nullptr, &jsthis, nullptr) != napi_ok) {
        return result;
    }
    NapiClassTest *obj;
    status = napi_unwrap(env, jsthis, (void **)&obj);

    if (obj->testMsg.length() > 0) {
        msg = obj->testMsg;
    }
    if (napi_create_string_utf8(env, msg.c_str(), msg.length(), &result) != napi_ok) {
        return result;
    }
    return result;
}

napi_value NapiClassTest::Constructor(napi_env env, napi_callback_info info)
{
    napi_value undefineVar = nullptr, thisVar = nullptr;
    napi_get_undefined(env, &undefineVar);

    if (napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr) == napi_ok && thisVar != nullptr) {
        NapiClassTest *reference = new NapiClassTest();
        if (napi_wrap(env, thisVar,
            reinterpret_cast<void *>(reference), NapiClassTest::Destructor, nullptr, nullptr) == napi_ok) {
            return thisVar;
        }
        return thisVar;
    }
    return undefineVar;
}

void NapiClassTest::Destructor(napi_env env, void *nativeObject, void *finalize)
{
    delete reinterpret_cast<NapiClassTest *>(nativeObject);
}

void AkiClassTest::SetMsg(std::string msg)
{
    if (msg.length() > 0) {
        testMsg = msg;
    }
}

std::string AkiClassTest::GetMsg()
{
    std::string msg = "hello NapiTest";
    if (testMsg.length() > 0) {
        return testMsg;
    }
    return msg;
}
}

